﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NAudio.Wave;
using System.IO;

namespace slCommunicator
{
    public class Recorder
    {
        private static bool recording = false;
        private static MemoryStream ms1;
        private static MemoryStream ms2;
        public static void NewRecording()
        {
            if (!Properties.Settings.Default.audio_recordCall)
                return;

            ms1 = new MemoryStream();
            ms2 = new MemoryStream();
            recording = true;
            Console.WriteLine(localization.recorder_start);
        }

        public static void DataIn(byte[] audio, bool b)
        {
            if (!recording)
                return;
            if (b)
                ms1.Write(audio, 0, audio.Length);
            else
                ms2.Write(audio, 0, audio.Length);
        }
        public static void EndRecording()
        {
            if (!recording)
                return;

            BufferedWaveProvider bwp1 = BwpFromRawMs(ms1);
            BufferedWaveProvider bwp2 = BwpFromRawMs(ms2);

            
            var mixer = new WaveFloatTo16Provider(new MixingWaveProvider32(new IWaveProvider[]{new Wave16ToFloatProvider(bwp1), new Wave16ToFloatProvider(bwp2)}));
            byte[] buffer = new byte[Math.Max(bwp1.BufferLength, bwp2.BufferLength)];
            mixer.Read(buffer, 0, buffer.Length);
            string outputfile = saveBytesToMp3(buffer);

            bwp1.ClearBuffer();
            bwp2.ClearBuffer();
            ms1 = null;
            ms2 = null;
            mixer = null;
            bwp1 = null;
            bwp2 = null;
            buffer = null;
            recording = false;
            Console.WriteLine(localization.recorder_endedSaved, outputfile);
        }

        private static BufferedWaveProvider BwpFromRawMs(MemoryStream ms)
        {
            BufferedWaveProvider bwp = new BufferedWaveProvider(DuplexAudio.wformat);
            bwp.BufferLength = (int)ms.Length;

            byte[] b = ms.ToArray();
            bwp.AddSamples(b, 0, b.Length);
            ms.Close();

            return bwp;
        }

        private static string saveBytesToMp3(byte[] data)
        {
            string filename = DateTime.Now.ToString("d-MMM-yyyy h-mm-ss.ff t") + ".mp3";
            NAudio.Lame.LameMP3FileWriter lame = new NAudio.Lame.LameMP3FileWriter(filename, DuplexAudio.wformat, 32);

            lame.Write(data, 0, data.Length);

            lame.Close();
            return filename;
        }
    }
}
